package com.cimu.qiniu.controller;

import com.cimu.qiniu.dto.UploadDto;
import com.cimu.qiniu.service.QiniuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Title: QiNiuController
 * Copyright: Copyright (c) 2017
 *
 * date 2019年01月07日 09:17
 */
@Controller
@RequestMapping("/qiniu")
@Slf4j
public class QiNiuController {
    @Autowired
    private QiniuService qiniuService;

    /**
     * 访问页面
     * @param model
     * @return
     */
    @GetMapping(value = "/index")
    public String findOneCity(Model model) {
        return "qiniu";
    }

    /**
     * 获取token
     * @return
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/token")
    public Object token() {
        return qiniuService.getToken();
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/upload")
    public Object uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = qiniuService.uploadSuffix(file.getBytes(), suffix);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("fileName", fileName);
        resultMap.put("fileUrl", qiniuService.getFileUrl(fileName));
        return resultMap;
    }

    /**
     * 文件上传完回调
     *
     * @param request HttpServletRequest
     * @return JsonObject 返回值
     */
    @PostMapping("/callback")
    public Object callback(HttpServletRequest request) throws IOException {
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        // 设置返回给七牛的数据
        log.info("回调内容：{}", sb.toString());
        UploadDto file = qiniuService.fileCallback(request.getHeader("Authorization"), sb.toString());
        return file;
    }

}
